<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils'
import { importEmployee } from '@/api/employees'

export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 数据处理
    newdata(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map((item) => {
        const obj = {}
        const k = Object.keys(item)
        k.forEach((key) => {
          if (mapInfo[key] === 'timeOfEntry' || mapInfo[key] === 'correctionTime') {
            return (obj[mapInfo[key]] = new Date(formatExcelDate(item[key], '-')))
          }
          obj[mapInfo[key]] = item[key]
        })
        return obj
      })
    },
    async handleSuccess({ results, header }) {
      const data = this.newdata(results)
      console.log(data)
      const res = await importEmployee(data)
      console.log(res)
    }
  }
}
</script>
